//@login & register
const express=require("express");
const router =express.Router();
const Profile=require("../../model/profile");
const passpord=require("passport");


router.get("/test",(req,res)=>{
    res.json({msg:"profiles works"})
})

// @route  POST api/profiles/add
// @desc   添加信息
// @access private
router.post("/add",passpord.authenticate("jwt",{session:false}),(req,res)=>{
    const profileFields={};
    if(req.body.type) profileFields.type=req.body.type;
    if(req.body.description) profileFields.description=req.body.description;
    if(req.body.income) profileFields.income=req.body.income;
    if(req.body.expend) profileFields.expend=req.body.expend;
    if(req.body.cash) profileFields.cash=req.body.cash;
    if(req.body.remark) profileFields.remark=req.body.remark;

    new Profile(profileFields).save().then((profile)=>{
        console.log(profile);
        res.json(profile);
    })
});

// @route  POST api/profiles/
// @desc   获取信息
// @access private

router.get("/",passpord.authenticate("jwt",{session:false}),(req,res)=>{
    Profile.find()
        .then(profile=>{
            if(!profile){
                return res.status(404).json('没有数据');
            }
            return res.json(profile);
        })
        .catch(err=> res.status(404).json(err));
});

// @route  POST api/profiles/:id
// @desc   获取单个信息
// @access private

router.get("/:id",passpord.authenticate("jwt",{session:false}),(req,res)=>{
    Profile.findOne({_id:req.params.id})
        .then(profile=>{
            if(!profile){
                return res.status(404).json('没有数据');
            }
            return res.json(profile);
        })
        .catch(err=> res.status(404).json(err));
});

// @route  POST api/profiles/edit
// @desc   修改信息
// @access private
router.post("/edit/:id",passpord.authenticate("jwt",{session:false}),(req,res)=>{
    const profileFields={};
    if(req.body.type) profileFields.type=req.body.type;
    if(req.body.description) profileFields.description=req.body.description;
    if(req.body.income) profileFields.income=req.body.income;
    if(req.body.expend) profileFields.expend=req.body.expend;
    if(req.body.cash) profileFields.cash=req.body.cash;
    if(req.body.remark) profileFields.remark=req.body.remark;


    Profile.findOneAndUpdate(
        {_id:req.params.id},
        {$set:profileFields},
        {new:true}
        ).then(profile=>res.json(profile));
});

// @route  POST api/profiles/delete/:id
// @desc   修改信息
// @access private

router.delete(
    '/delete/:id',
    passpord.authenticate('jwt', { session: false }),
    (req, res) => {
      Profile.findOneAndRemove({ _id: req.params.id })
        .then(profile => {
          profile.save().then(Profile.find().then(profiles=>{
              return res.json(profiles);
          }));
        })
        .catch(err => res.status(404).json('删除失败!'));
    }
  );
module.exports=router;
